<template>
  <div class="container  order-list">
    <!-- 面包屑导航 -->
    <breadcrumb :breadcrumbConfig=breadcrumbConfig></breadcrumb>
    <!--    <breadcrumb></breadcrumb>-->
    <!-- 面包屑导航 -->

    <div class="content page-title">
      <h2>修改订单</h2>
      <div class="headerbox_right">
        <!-- <el-button size="mini" @click="back()">返回</el-button> -->
      </div>
    </div>
    <!--
    <div class="step">
      <el-steps :active="stepsActive" align-center>
        <el-step v-for="(item,index) in stepsData.list" :title="item" :key="index"></el-step>
      </el-steps>
    </div>
    -->
    <!-- 选购商品步骤 -->
    <div class="content" v-if="stepsActive==1">
      <h3>数据筛选</h3>
      <form-filed class="search-form" :formconfig="searchFormConfig.formconfig" :formData="searchFormConfig.formData"
                  @formDataval="dialogClick" ref="formAttr"/>
    </div>
    <div class="box" v-if="stepsActive==1">
      <div class="headerTitle">商品列表</div>
      <el-tabs v-model="activeName" @tab-click="getClickTabList">
        <el-tab-pane label="选择商品" name="goods">
          <span slot="label">
        <span>选择商品({{ titleNum.totalCount ? titleNum.totalCount : 0 }})</span>
          </span>
        </el-tab-pane>
        <el-tab-pane label="选择赠品" name="second">
           <span slot="label">
        <span>选择赠品({{ titleNum.giftCount ? titleNum.giftCount : 0 }})</span>
          </span>
        </el-tab-pane>
      </el-tabs>
      <lb-table
          :column="columns"
          :data="page.list"
          pagination
          max-height="400"
          :total="page.totalNum"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20, 30, 50]"
          :current-page.sync="page.currentPage"
          :page-size="page.pageSize"
          @size-change="handleSizeChange"
          @p-current-change="handleCurrentChange"
          :default-sort="{prop: 'date', order: 'descending'}"
          @sort-change="handleSort"
      >
      </lb-table>
    </div>
    <!-- 提交订单步骤 -->
    <div class="content" v-if="stepsActive==2">
      <h3>基础信息</h3>
      <!-- //产品说客户意向，等级，入线方式隐藏不显示 -->
      <div class="details">
        <div class="details_item">
          <div class="details_title">客户姓名</div>
          <div class="details_value">{{ clientMessage.userName ? clientMessage.userName : '-' }}</div>
        </div>
        <div class="details_item">
          <div class="details_title">手机号码1</div>
          <div class="details_value">{{ clientMessage.phone1 ? clientMessage.phone1 : '-' }}</div>
        </div>
        <div class="details_item">
          <div class="details_title"> 手机号码2</div>
          <div class="details_value">{{ clientMessage.phone2 ? clientMessage.phone2 : '-' }}</div>
        </div>
        <div class="details_item">
          <div class="details_title">性别</div>
          <div class="details_value">{{ clientMessage.genderCN }}</div>
        </div>
        <div class="details_item">
          <div class="details_title">年龄</div>
          <div class="details_value">{{ clientMessage.age ? clientMessage.age : '-' }}</div>
        </div>
        <div class="details_item">
          <div class="details_title">购买次数</div>
          <div class="details_value">{{ buyNumber }}</div>
        </div>
        <div class="details_item">
          <div class="details_title">创建时间</div>
          <div class="details_value">{{ clientMessage.createdTimeNew ? clientMessage.createdTimeNew : '-' }}</div>
        </div>
        <div class="details_item">
          <div class="details_title"></div>
          <div class="details_value">
            <!-- <el-select size="mini" v-model="customerIntention" placeholder="请选择" style="width:100%;">
              <el-option
                v-for="item in dictionaries.customer_intention"
                :key="item.dictId"
                :label="item.dictName"
                :value="item.dictId">
              </el-option>
            </el-select> -->
          </div>
        </div>
        <div class="details_item">
          <div class="details_title"></div>
          <div class="details_value"></div>
        </div>
        <div class="details_item">
          <div class="details_title"></div>
          <div class="details_value"></div>
        </div>
      </div>
    </div>
    <div class="content" v-if="stepsActive==2">
      <div class="addressBox">
        <div class="headerTitle shopTitle">选择收货地址</div>
        <div class="addressHeader" v-if="siteDataList.length==0">
          <i class="el-icon-circle-plus-outline" style="color: #4168e7"></i>
          <el-button style="color: #4168e7;" type="text" @click="addLocation()">新增收货地址</el-button>
        </div>
      </div>
      <el-table
          :data="siteDataList"
          stripe
          style="width: 100%"
          class="site-data-list"
          :header-cell-style="{background: '#faf7fa',color:'#333333'}"
      >
        <el-table-column label="收货人" prop="userName"></el-table-column>
        <el-table-column label="手机号码" prop="phone"></el-table-column>
        <el-table-column label="地区" prop="userName">
          <template slot-scope="props">
            <p>
              {{
                props.row.provinceCode ? props.row.provinceCode +
                    props.row.cityCode +
                    props.row.regionCode : '-'
              }}
            </p>
          </template>
        </el-table-column>
        <el-table-column label="详细地址" prop="detailedAddress">
        </el-table-column>
        <el-table-column label="默认地址">
          <template slot-scope="props">
            <el-switch
                v-model="props.row.isDefault"
                :active-value="1"
                :inactive-value="0"
                @change="defaultSite(props.row.id)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="props">
            <el-button
                type="text"
                @click="amendAddress('addressEdit')"
            >更改
            </el-button>

          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="orderBox">
      <div class="order">
        <p class="headerTitle shopTitle">已选商品</p>
        <!--        <el-table :data="tableData" style="width: 100%">-->
        <el-table :data="orderDetailList" style="width: 100%">
          <el-table-column min-width="200px" label="商品信息" header-align="left">
            <template slot-scope="scope">
              <div class="goodsBox">
                <div class="imgBox">
                  <!--                  <img :src="scope.row.mainImage"/>-->
                  <el-image :src="scope.row.mainImage" :preview-src-list="scope.row.mainImageArr"
                            fit="cover"></el-image>
                </div>
                <div class="goodsBox_title">
                  <h3><span>{{ scope.row.name }}</span></h3>
                  <p v-html="scope.row.specTitle"></p>
                  <p class="goods-id">商品编号：{{ scope.row.goodsNo }}</p>
                  <span v-if="scope.row.goodsType==3 || scope.row.goodsType=='赠品'" class="gift">赠品</span>
                </div>

              </div>
            </template>
          </el-table-column>
          <el-table-column label="单价/数量" header-align="left" prop="quantity">
            <template slot-scope="scope">
              <div style="text-align: center" class="table-price">
                <p class="retail-price"><label>零售价：</label><el-input size="mini" v-model.number="scope.row.retailPrice" ></el-input></p>
                <p>市场价：￥{{ scope.row.marketPrice.toFixed(2) }}</p>
                <p v-if="stepsActive==2" style="color: #999999">x{{ scope.row.quantity }}</p>
                <p v-if="stepsActive==1">
                  <el-input-number size="mini" v-model="scope.row.quantity" :min="1" label="描述文字"></el-input-number>
                </p>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="total" label="小计" header-align="right">
            <template slot-scope="scope">
              <!--              <p  style="text-align: right">实付￥{{ parseFloat(scope.row.total).toFixed(2) }}</p>-->
              <p style="text-align: right">实付￥{{ parseFloat(scope.row.totalRetailPrice).toFixed(2) }}</p>
              <p style="text-align: right">￥{{ parseFloat(scope.row.totalMarketPrice).toFixed(2) }}</p>
            </template>
          </el-table-column>
          <el-table-column min-width="120px" label="操作" header-align="right" v-if="stepsActive==1">
            <template slot-scope="scope">
              <div style="text-align: right">
                <el-button type="text" @click="delectSelect(scope.$index)">移除商品</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="orderNotes">
        <div class="headerOrder">
          <div class="orderRemak">订单备注</div>
        </div>
        <div class="notes">
          <el-input
              maxlength="200"
              type="textarea"
              show-word-limit
              v-model="textarea"
              placeholder="备注"
          ></el-input>

        </div>
      </div>
      <div class="statistics">
        <p class="fourteen">
          <span>总计：共 {{ totalNumber ? totalNumber : '0' }} 件 </span>
        </p>
        <p class="fourteen">
          <span>商品总价：￥{{ totalPrice ? totalPrice : '0' }}</span>
        </p>
        <p class="fourteen">
          <span>运费￥{{ giftPrice ? giftPrice : '0' }}</span>
        </p>
        <p style="margin-right:20px">
          <span class="blue">应付:￥<span v-if="stepsActive==2">{{ dealWithNew ? dealWithNew : '0' }}</span></span>
          <span v-if="stepsActive==1">
              <el-input-number :controls="false" style="width:80px" :precision="2" size="mini" v-model="dealWithNew"
                               placeholder=""></el-input-number>
            </span>
        </p>
        <p style="margin-right:20px">
          <span v-if="stepsActive==1">
            <span class="blue">已收:￥</span>
            <span>
              <el-input-number :controls="false" @blur="handlerReceivedMoney" style="width:80px" :precision="2"
                               size="mini" v-model.trim="receivedMoney" placeholder=""></el-input-number>
            </span>
          </span>
          <span v-if="stepsActive==2">
            <span class="blue">(已收:￥<span>{{ receivedMoney ? receivedMoney : '0' }}</span>)</span>
          </span>
        </p>
      </div>
      <div class="auditRadio" v-if="stepsActive==2&&auditStatus!=-1">
        <span>是否审核:</span>
        <div>
          <el-radio-group v-model="radioForm.resource">
            <el-radio :disabled="whether" label="1">是</el-radio>
            <el-radio :disabled="whether" label="0">否</el-radio>
          </el-radio-group>
        </div>
      </div>
    </div>
    <div class="present">
      <el-button v-if="stepsActive==2" @click="cancelOrder" class="cancel-order">取消订单</el-button>
      <el-button type="primary" @click="activeSubmit">生成订单</el-button>
    </div>
    <!--========================== el-dialog =================================-->
    <el-dialog :title="dialog.title" :visible.sync="dialog.visible" append-to-body :width="dialog.width">
      <template v-if="dialog.type == 'moreSpecification'">
        <div v-for="(item,index) in specList " :key="index" class="skuBox">
          <div class='title'>{{ item.name }}</div>
          <div class='spec'>
            <div class='spec-item' v-for="(its,ins) in item.specItemList" :key="its.content + ins">
              <span @click="changeSpec(item.name, its.content)"
                    :class="[selectSpec[item.name] == its.content ? 'active' : '']">{{ its.content }}</span>
            </div>
          </div>
        </div>
        <div class="specificationBox">
          <p class="specificationBox_title">
            <span class="specificationBox_title_item">已选规格：</span><span class="specificationBox_title_right"><b
              v-if="matchingStr == ''">未选择</b><b v-else v-html="matchingStr"></b></span>
          </p>
          <div class="specificationBox_border">
            <div class="specificationBox_border_item">
              <span class="item">市场价</span> <span class="item">零售价</span> <span class="item">销量</span> <span
                class="item">库存</span>
            </div>
            <div class="specificationBox_border_money">
              <span class="item">{{ matching.marketPrice ? '￥' + matching.marketPrice : '-' }}</span>
              <span class="item">{{ matching.retailPrice ? '￥' + matching.retailPrice : '-' }}</span>
              <span class="item">{{ matching.soldNum || matching.soldNum === 0 ? matching.soldNum : '-' }}</span>
              <span class="item">{{ matching.stock ? matching.stock : '-' }}</span>
            </div>
          </div>
        </div>
        <div class="dialogBtnright" style="margin-top:20px">
          <el-button class="setPay_payment_btn_quxiao" @click="handledeleteClose">取 消</el-button>
          <el-button class="setPay_payment_btn_queren" type="primary" @click="addSelectList">确 定</el-button>
        </div>
      </template>
      <!-- 修改默认地址 -->
      <template v-if="dialog.type=='addressAmend'">
      <span class="addressHeader">
          <i class="el-icon-circle-plus-outline" style="color: #4168e7"></i>
          <el-button style="color: #4168e7;" type="text" @click="addAddress('Address')">新增收货地址</el-button>
        </span>
        <el-table
            :data="addressDataList"
            :header-cell-style="{background: '#F8F8F9',color:'#333333'}"
        >
          <el-table-column label="收货人" prop="userName"></el-table-column>
          <el-table-column label="手机号码" prop="phone"></el-table-column>
          <el-table-column label="地区" prop="userName">
            <template slot-scope="props">
              <p>
                {{
                  props.row.provinceCode +
                  props.row.cityCode +
                  props.row.regionCode
                }}
              </p>
            </template>
          </el-table-column>
          <el-table-column label="详细地址" prop="detailedAddress">
          </el-table-column>
          <el-table-column label="默认地址">
            <template slot-scope="props">
              <el-switch
                  v-model="props.row.isDefault"
                  :active-value="1"
                  :inactive-value="0"
                  @change="defaultSite(props.row.id)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="props">
              <el-button
                  type="text"
                  @click="employ(props.row)"
              >使用
              </el-button>
              <el-button
                  type="text"
                  @click="dialogEdit('editAddress', props.row)"
              >编辑
              </el-button>
              <el-button

                  style="color: red"
                  type="text"
                  @click="dialogDelete(props.row.id)"
              >删除
              </el-button>

            </template>
          </el-table-column>

        </el-table>

      </template>
      <!-- 新增收货地址 -->
      <template v-if="dialog.type == 'addAddress'||dialog.type =='addLocation'" class="addAddress">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="收货人姓名" label-width="100px" prop="userName" style="width:97%">
            <el-input v-model.trim="form.userName" placeholder="请输入收货人姓名"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" label-width="100px" prop="phone">
            <el-input
                placeholder="请输入联系电话"
                style="width:96%"
                oninput="value=value.replace(/[^0-9.]/g,'')"
                :maxLength="11"
                v-model.trim="form.phone"
            ></el-input>
          </el-form-item>
          <el-form-item
              label="收货地址"
              label-width="100px"
              prop="addressValue"
          >
            <el-cascader
                placeholder="请选择收货地址"
                style="width:96%"
                v-model="form.addressValue"
                :options="addressOptions"
                clearable
                filterable
                @change="onChangeAddress"
            ></el-cascader>
          </el-form-item>
          <el-form-item
              label="详细地址"
              label-width="100px"
              prop="detailedAddress"
          >
            <el-input v-model.trim="form.detailedAddress" placeholder="请输入详细地址" style="width:96%"></el-input>
            <el-checkbox
                v-model="form.isDefault"
                :false-label="0"
                :true-label="1"
            >设为默认
            </el-checkbox>
          </el-form-item>
          <div class="dialogBtn">
            <el-button class="setPay_payment_btn_quxiao" @click="dialog.visible = false">取 消</el-button>
            <el-button class="setPay_payment_btn_queren" type="primary" @click="dialogSubmit('form')"
            >确 定
            </el-button
            >
          </div>
        </el-form>
      </template>

      <!-- 支付方式 -->
      <template v-if="dialog.type == 'selectPay'">
        <el-radio-group v-model="setPay.payment" @change="selectPayment">
          <el-radio label="1">在线支付</el-radio>
        </el-radio-group>
        <div class="setPayDialogBtn">
          <div>
            <el-checkbox-group v-model="setPay.payDefault" @change="selectPayDefault">
              <el-checkbox label="1" name="type">设为默认</el-checkbox>
            </el-checkbox-group>
          </div>
          <div>
            <el-button class="setPay_payment_btn_quxiao" @click="dialog.visible = false">取 消</el-button>
            <el-button class="setPay_payment_btn_queren" type="primary" @click="confirmSelectPay">确 定</el-button>
          </div>
        </div>
      </template>
      <!-- 支付方式 -->
      <template v-if="dialog.type == 'selectPayNew'">
        <el-radio-group v-model="selectPay" @change="selectPayment">
          <el-radio v-for="(item,index) in dictionaries.order_pay_type" class="setPay_payment" :key="index" :label="item.dictId">{{item.dictName}}</el-radio>
        </el-radio-group>
        <div class="setPayDialogBtn">
          <div>
          </div>
          <div>
            <el-button class="setPay_payment_btn_quxiao" @click="dialog.visible = false">取 消</el-button>
            <el-button class="setPay_payment_btn_queren" type="primary" @click="handlerSelectPay">确 定</el-button>
          </div>
        </div>
      </template>
      <!-- 在线支付 -->
      <template v-if="dialog.type == 'payMoney'">
        <div class="payMoney">
          <div>
            <p class="payMoney_should">应付:￥{{ dealWith ? dealWith : '0' }}</p>
            <p class="payMoney_already">已收:￥{{ receivedMoney ? receivedMoney : '0' }}</p>
          </div>
          <div class="payMoney_box">
            <span class="payMoney_money">支付金额</span><span class="payMoney_mo">￥</span>
            <el-input-number
                :controls="false"
                :mix="0"
                type="number"
                :precision="2"
                v-model="paymentAmount"
                style="width:110px"
            >
            </el-input-number>
          </div>
          <div class="payMoney_text">
            <span class="payMoney_text_item">总计: 共{{ totalNumber ? totalNumber : '0' }}件</span><span
              class="payMoney_text_item">商品总价: ￥{{ totalPrice ? totalPrice : '0' }}</span><span
              class="payMoney_text_item">运费: ￥{{ giftPrice ? giftPrice : '0' }}</span>
          </div>
        </div>
        <div class="dialogBtnright">
          <div>
            <el-button class="setPay_payment_btn_quxiao" @click="dialog.visible = false">取 消</el-button>
            <el-button class="setPay_payment_btn_queren" type="primary" @click="onlinePayment">确 定</el-button>
          </div>
        </div>
      </template>
    </el-dialog>

    <!--=========================== el-dialog end================================-->
  </div>

</template>

<script>
import formFiled from '@/components/form/index'
import breadcrumb from '@/components/breadcrumb'
import LbTable from '../../components/lb-table/lb-table'
import { spawn } from 'child_process'
import mixinsCommon from './mixins/common'
import mixinsSKU from './mixins/mixinsSKU'
import addressData from '@/components/addressData.js'
import mixinsAddModifyCommon from './mixins/mixinsAddModifyCommon'

export default {
  mixins: [mixinsCommon, mixinsSKU, mixinsAddModifyCommon],
  components: {
    formFiled,
    breadcrumb,
    LbTable,
    addressData
  },
  data () {
    return {
      modifyOrderDetails: {}, // 回显修改订单内容
      orderGoodsList: [], // 回显修改商品内容
      customerId: '' // 客户ID
    }
  },
  created () {
    this.initSearchCategoryList()// 初始化搜索数据 - 类目id
    this.initSearchBrandList() // 初始化搜索数据 - 品牌
    this.fetchData(0)
    // this.getPlaceGoodsCount()

    // this.categoryDetails()// 查询客户基本信息
    // this.shippingAddressList()// 查询收货地址
    this.trimAddressData() // 初始化地区数据
    this.getPassFlag() // 是否必审
    // this.id=this.$route.query.id;
    this.routeQuery = this.$route.query
    this.taskId = this.$route.query.taskId
    this.isChange = this.$route.query.isChange // 1为改单
    this.orderId = this.$route.query.orderId
    this.orderNo = this.$route.query.orderNo
    /*
    if (this.$route.query.userId) {
      this.customerId = this.$route.query.userId
    } else {
      this.open()
    }
    */
    this.addressId = this.$route.query.addressId
    this.pingZ = this.$route.query.pingZ
    if (this.$route.query.channelOrderId) {
      this.channelOrderId = this.$route.query.channelOrderId
    }

    if (!this.is_null(this.pingZ)) {
      this.pingZ = true
    }
    this.voucher = JSON.parse(sessionStorage.getItem('voucher'))
    if (!this.is_null(this.voucher)) {
      this.textarea = this.voucher.note
      this.fileList = this.voucher.fileImg
    }

    if (this.$route.query.orderCommodityList) {
      // 判断是否是路由传参
      this.tableData = this.$route.query.orderCommodityList
      for (const item of this.tableData) {
        item.title = item.name
        item.sellPrice = item.price
      }
      this.tableZp = this.$route.query.orderComplimentaryList
    } else {
      this.tableData = JSON.parse(sessionStorage.getItem('goodsList'))
      this.tableZp = JSON.parse(sessionStorage.getItem('giftList'))
    }

    if (!this.is_null(this.tableData)) {
      // this.tableData不为空，就执行计算
      for (let i = 0; i < this.tableData.length; i++) {
        this.arry.push(this.tableData[i].id)
      }
      for (let i = 0; i < this.tableZp.length; i++) {
        this.arrayZp.push(this.tableZp[i].id)
      }
      // this.calculation()
      this.receivedMoney = this.$route.query.receivedMoney
      this.total = this.$route.query.total
    } else {
      // if (!this.$route.query) {
      this.tableData = []
      // this.tableZp = []
      // }
    }
    this.brandSelectBox()
    this.brandSelect()
    // this.getDefaultAddress();
    document.onkeydown = (e) => {
      const key = window.event.keyCode
      if (key == 13) {
        this.searchGoods()
      }
    }
    if (this.$route.query.orderId) {
      this.getModifyOrderDetails(this.$route.query.orderId)
      this.getOrderGoodsList(this.$route.query.orderId)
    }
  },
  watch: {},
  computed: {},
  methods: {
    getModifyOrderDetails (orderId) {
      const params = { id: orderId }
      this.$api.getOrderDetail(params).then((res) => {
        if (res.code === 0) {
          const customerId = res.data.customerId
          this.customerId = res.data.customerId
          this.$router.push({query: {...this.$route.query,userId: customerId}})
          this.dealWithNew = res.data.receivableAmount
          // this.receivedMoney = res.data.receivedAmount
          this.modifyOrderDetails = res.data
          console.log(this.modifyOrderDetails)
          this.getNumber(customerId) // 购买次数
          // this.selectDefAddress(customerId) // 订单地址列表数据
          this.shippingAddressList(customerId)// 收货地址列表数据
          this.categoryDetails(customerId)// 查询客户基本信息
          this.textarea = res.data.remarks
          this.selectPay = res.data.payType
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    getOrderGoodsList (orderId) {
      const params = { id: orderId }
      this.$api.getOrderGoodsInfo(params).then((res) => {
        if (res.code === 0) {
          // console.log(res.data)
          res.data.forEach((item, index) => {
            // const indexLength = this.orderDetailList.length
            // this.$set(this.orderDetailList, indexLength, item)
            item.name = item.goodsName
            item.mainImageArr = []
            item.mainImageArr.push(item.goodsImage)
            item.mainImage = item.goodsImage
            // item.marketPrice = 1
            // item.retailPrice = 2
            item.specTitle = ''
            if (item.specList.length > 0) {
              item.specList.forEach(specListItem => {
                item.specTitle += specListItem.specName + '/' + specListItem.specItemName + '&ensp;'
              })
            }
            // item.specTitle = tempStr
            this.$set(this.orderDetailList, index, item)
          })
          // console.log(this.orderDetailList)
        }
      }).catch((err) => {
        console.log(err)
      })
    },

    // 第一层新增收货地址
    addLocation () {
      this.dialog.type = 'addLocation'
      this.dialog.title = '新增地址'
      this.dialog.visible = true
      this.dialog.width = '450px'
      this.form.userName = ''
      this.form.phone = ''
      this.form.detailedAddress = ''
      this.form.addressValue = ''
      this.form.isDefault = 0
      this.form.provinceCode = ''
      this.form.cityCode = ''
      this.form.regionCode = ''
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    // 接受表单组件的数据
    dialogClick (val) {
      this.searchFormVal = Object.assign({}, val)
      this.fetchData()
    },
    cancelOrder () {
      this.stepsActive = 1
    },
    // 新增收货地址
    addAddress (type, row) {
      if (this.dialog.type == 'addressAmend') {
        this.dialog.visible = false
        this.dialog.type = 'addAddress'
        this.dialog.title = '新增地址'
        this.dialog.visible = true
        this.dialog.width = '450px'
        this.form.userName = ''
        this.form.phone = ''
        this.form.detailedAddress = ''
        this.form.addressValue = ''
        this.form.isDefault = 0
        this.form.provinceCode = ''
        this.form.cityCode = ''
        this.form.regionCode = ''
        this.$nextTick(() => {
          this.$refs['form'].clearValidate()
        })
      }
    },
    // 地区修改
    onChangeAddress (val) {
      const addressOptions = this.addressOptions
      for (let i = 0; i < val.length; i++) {
        if (i === 0) {
          this.form.provinceCode = addressOptions[val[0]].label
          continue
        }
        if (i === 1) {
          this.form.cityCode = addressOptions[val[0]].children[val[1]].label
          continue
        }
        if (i === 2) {
          this.form.regionCode = addressOptions[val[0]].children[val[1]].children[val[2]].label
          continue
        }
      }
    },
    // 修改收货地址弹框列表里面的使用地址
    employ (row) {
      this.siteDataList = []
      this.siteDataList.push(row)
      this.dialog.visible = false
    },
    // 初始化地区数据
    trimAddressData () {
      const arr = []
      for (const province in addressData) {
        const childrenCity = []
        for (const city in addressData[province]) {
          const childrenArea = []
          addressData[province][city].forEach((e, i) => {
            childrenArea.push({ title: '市区', label: e, value: i })
          })
          childrenCity.push({ title: '城市', label: city, children: childrenArea, value: city })
        }
        arr.push({ title: '省份', label: province, children: childrenCity, value: province })
      }
      // 修改 value 值
      arr.forEach((e, i) => {
        e.value = i
        e.children.forEach((ee, ii) => {
          ee.value = ii
        })
      })
      this.addressOptions = arr
    },
    // 编辑/修改提交数据
    dialogSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialog.title == '编辑') {
            const data = {
              // userId: this.$route.query.userId,
              userId: this.customerId,
              userName: this.form.userName,
              phone: this.form.phone,
              provinceCode: this.form.provinceCode, // 省
              cityCode: this.form.cityCode, // 市
              regionCode: this.form.regionCode, // 区
              detailedAddress: this.form.detailedAddress,
              isDefault: this.form.isDefault,
              id: this.rowId
            }
            this.$api.categoryEditaddress(data).then((res) => {
              if (res.code == 0) {
                this.$message.success('修改成功')
                this.dialog.visible = false
                this.shippingAddressList()
                // setTimeout(() => {
                //   this.selectDefAddress()
                // }, 100)
                this.$forceUpdate()
              }
            }).catch((err) => {
              console.log(err)
            })
          } else {
            const data = {
              // userId: this.$route.query.userId,
              userId: this.customerId,
              userName: this.form.userName,
              phone: this.form.phone,
              provinceCode: this.form.provinceCode, // 省
              cityCode: this.form.cityCode, // 市
              regionCode: this.form.regionCode, // 区
              detailedAddress: this.form.detailedAddress,
              isDefault: this.form.isDefault
            }
            this.$api.categoryAddaddress(data).then((res) => {
              if (res.code == 0) {
                this.$message.success('新增成功')
                this.dialog.visible = false
                // setTimeout(() => {
                //   this.selectDefAddress()
                // }, 200)
                setTimeout(() => {
                  this.shippingAddressList()
                }, 300)
              }
            }).catch((err) => {
              console.log(err)
            })
          }
        } else {
          return false
        }
      })
    },
    // 编辑按钮
    dialogEdit (type, row) {
      // this.$refs.addCustomers.clickData()
      this.form.addressValue = []
      this.addressOptions.find(province => {
        if (province.label == row.provinceCode) {
          this.form.addressValue.push(province.value)

          province.children.find((city) => {
            if (city.label == row.cityCode) {
              this.form.addressValue.push(city.value)
            }
            city.children.find((district) => {
              if (district.label == row.regionCode) {
                this.form.addressValue.push(district.value)
              }
            })
          })
        }
      })
      this.dialog.type = 'addAddress'
      this.dialog.title = '编辑'
      this.dialog.width = '450px'
      this.dialog.visible = true
      this.form.userName = row.userName
      this.form.phone = row.phone
      this.form.detailedAddress = row.detailedAddress
      this.form.isDefault = row.isDefault
      this.rowId = row.id
      this.form.provinceCode = row.provinceCode
      this.form.cityCode = row.cityCode
      this.form.regionCode = row.regionCode
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    // 修改收货地址
    amendAddress () {
      this.dialog.visible = true
      this.dialog.title = '修改收货地址'
      this.dialog.type = 'addressAmend'
      this.dialog.width = '1274px'
      this.shippingAddressList()
    },
    // 删除地址
    dialogDelete (id) {
      this.$confirm('是否删除该地址？', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          addressId: id,
          // userId: this.$route.query.userId
          userId: this.customerId
        }
        this.$api.categoryDeleteAddress(params).then(res => {
          if (res.code == 0) {
            this.$message.success('删除成功！')
            this.shippingAddressList()
            // setTimeout(() => {
            //   this.selectDefAddress()
            // }, 100)
            this.$forceUpdate()
          }
        }).catch((err) => {
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 是否设置为默认地址
    defaultSite (id) {
      this.setCategoryDefaultSite(id)
    },
    // 设置默认地址
    setCategoryDefaultSite (id) {
      const params = {
        id: id
      }
      this.$api.categoryDefaultSite(params).then((res) => {
        if (res.code == 0) {
          this.$message.success('设置成功！')
          this.shippingAddressList()
          // setTimeout(() => {
          //   this.selectDefAddress()
          // }, 100)
          this.$forceUpdate()
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // // 订单地址列表数据
    // selectDefAddress (customerId) {
    //   this.siteDataList = []
    //   const userId = customerId || this.customerId
    //   // const userId = 1
    //   const params = { userId }
    //   this.$api.selectDefAddress(params).then((res) => {
    //     if (res.code === 0 && res.data) {
    //       if (this.siteDataList.length == 0) {
    //         this.$nextTick(() => {
    //           this.siteDataList.push(res.data)
    //         })
    //       }
    //       this.$forceUpdate(this.siteDataList,'this.siteDataList')
    //       console.log()
    //     }
    //   }).catch(err => {
    //     console.log(err)
    //   })
    // },
    // 收货地址列表数据
    shippingAddressList (customerId) {
      const userId = customerId || this.customerId
      const params = { id: userId }
      this.$api.categoryShippingAddress(params).then((res) => {
        if (res.code == 0) {
          this.addressDataList = res.data
        console.log(this.addressDataList,'this.addressDataList')

          this.$forceUpdate()
          if (this.siteDataList.length == 0 && this.addressDataList.length != 0) {
            res.data.forEach((item)=>{
              if(item.id == this.modifyOrderDetails.addressId){
              this.siteDataList.push(item)
              }
            })
            if(this.siteDataList.length==0){
              this.siteDataList.push(this.addressDataList[this.addressDataList.length - 1])
            }
            this.$forceUpdate()
          }
          this.$forceUpdate()
        }
        console.log(this.siteDataList,'this.siteDataList')
      }).catch(err => {
        console.log(err)
      })
    },
    // 查询客户基本信息
    categoryDetails (customerId) {
      // const userId = sessionStorage.getItem('user_id')
      // const userId = sessionStorage.getItem('user_id')
      const userId = customerId
      const params = { id: userId }
      this.$api.categoryDetails(params).then(res => {
        if (res.code === 0) {
          res.data.createdTimeNew = res.data.createdTime.split(' ')[0]
          if (res.data.gender == 1) {
            res.data.genderCN = '男'
          } else if (res.data.gender == 2) {
            res.data.genderCN = '女'
          } else {
            res.data.genderCN = '未知'
          }
          this.clientMessage = res.data
        }
      })
    },
    // 关闭弹框
    handledeleteClose () {
      this.dialog.visible = false
    },
    // 下单-选购商品数量统计查询接口
    getPlaceGoodsCount (params) {
      // const params = {}
      this.$api.getPlaceGoodsCount(params).then((res) => {
        if (res.code === 0) {
          this.titleNum = res.data
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 显示  dialog
    showDialogshowDialog (title, type, row) {
      this.dialog.type = type
      this.currentRow = row
    },
    getClickTabList (tab) {
      this.tabIndex = tab.index
      this.fetchData(tab.index)
    },
    is_null (content) {
      if (content) {
        return false
      } else {
        return true
      }
    },
    reset () {
      this.goods = {
        name: '',
        brand: '',
        category: [],
        code: ''
      }
      this.currentPageZp = 1
      this.pageSizeZp = 10
      this.currentPage1 = 1
      this.pageSizegoods = 10

      this.fetchData()
      this.giftList()
    },
    searchGoods () {
      this.currentPage1 = 1
      this.pageSizegoods = 10
      this.fetchData()
    },
    searhgift () {
      this.currentPageZp = 1
      this.pageSizeZp = 10
      this.giftList()
    },

    //* * 品牌下拉 **//
    brandSelectBox () {
      this.axios
        .get('/order/comm/commodity/selectList', {
          headers: {
            isLoading: false
          }
        })
        .then((res) => {
          if (res.code == 0) {
            this.brandselect = res.data
          } else {
            this.$message.error(res.message)
          }
        })
    },
    //* * 品牌下拉 **//
    // 分类下拉框
    brandSelect () {
      this.axios
        .get('/order/comm/commodity/selectBrand', {
          headers: {
            isLoading: false
          }
        })
        .then((res) => {
          if (res.code == 0) {
            this.options = res.data
          } else {
            this.$message.error(res.message)
          }
        })
    },
    handleChange (currentValue, lodValue, row) {
      // const quantity = item.quantity
      this.$nextTick(() => {
        setTimeout(() => {
          row.quantity = Number(currentValue)
        }, 10)
      })
    },
    handleChangeZp (val) {
      this.currentPageZp = val
      this.giftList()
    },
    handleSizeChangeZp (val) {
      this.pageSizeZp = val
      this.giftList()
    },
    // 数量文本框值改变
    changeCount (row, index) {
      if (
        row.number == null ||
          row.number == '' ||
          (row.number != 'number' && isNaN(row.number))
      ) {
        row.number = 1
      } else if (row.number <= 1) {
        row.number = 1
        this.$message({
          message: '已经减到最低了哦',
          type: 'warning'
        })
      }
      this.$set(this.tableData, index, {
        createdTime: row.createdTime,
        id: row.id,
        number: row.number,
        sellPrice: row.sellPrice,
        specificationName: row.specificationName,
        title: row.title,
        total: parseFloat(row.number * row.sellPrice).toFixed(2),
        brandId: row.brandId,
        typeId: row.typeId
      })
      this.tableData[index].number = row.number
      // this.calculation()
    },
    /** 修改商品的单价**/
    changePrice (row, index) {
      if (!this.is_null(row.sellPrice)) {
        this.$set(this.tableData, index, {
          createdTime: row.createdTime,
          id: row.id,
          number: row.number,
          sellPrice: row.sellPrice,
          specificationName: row.specificationName,
          title: row.title,
          total: parseFloat(Number(row.number) * Number(row.sellPrice)).toFixed(
            2
          ),
          brandId: row.brandId,
          typeId: row.typeId
        })
      } else {
        this.$message.warning('单价不能为空')
      }
      // this.calculation()
    },
    // 删除
    delectRow (index) {
      this.tableData.splice(index, 1)
      this.arry.splice(index, 1)
      // this.calculation()
    },

    notesEvent () {
      const notes = {
        note: this.textarea,
        fileImg: this.fileList
      }
      sessionStorage.setItem('voucher', JSON.stringify(notes))
    },
    // 选择支付方式弹框内的设置默认
    selectPayDefault (e) {
      if (this.setPay.payment) {
        if (e == true) {
          localStorage.setItem('Payment', 1)
          localStorage.setItem('PayDefault', true)
        } else {
          localStorage.removeItem('Payment')
          localStorage.removeItem('PayDefault')
        }
      }
    },
    // 选择支付方式
    selectPayment (e) {
      if (e == 1) { // 在线支付
        this.payStatus = e
      }
    },
    // 支付方式确定
    onlinePayment () {
      const data = {
        orderId: this.orderId,
        receivedAmount: this.paymentAmount
      }
      this.$api.onlinePay(data).then(res => {
        if (res.code == 0) {
          // this.$message.success('操作成功！')
          this.dialog.visible = false
          this.$notify({
            title: '成功',
            message: '操作成功 ！',
            type: 'success'
          })
        }
      })
    },
    // 生成收款码确定弹框
    confirmSelectPay () {
      if (this.dialog.type == 'selectPay') {
        this.dialog.visible = false
        if (this.setPay.payment != 1) {
          this.$message.warning('请选择支付方式！')
        }
        if (this.setPay.payment == 1) { // 1表示在线支付
          this.dialog.type = 'payMoney'
          this.dialog.visible = true
          this.dialog.title = '在线支付'
          this.dialog.width = '640px'
          this.paymentAmount = 0.00
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import './assets/addModifyCommon.scss';
/deep/ .el-image {
  width: 100px !important;
  height: 80px !important;
  overflow: hidden;

  img {
    width: 100%;
    object-fit: cover;
  }
}
 .setPay_payment{
    display: block;
    margin-bottom: 15px;
    margin-left: 25px
  }
</style>
